<template>
    <div class="editor-container">
        <div class="editor-toolbar">
            <div class="tool-group left">
                <n-button-group>
                    <n-button secondary @click="save">
                        <template #icon><n-icon>
                                <SaveOutline />
                            </n-icon></template>
                        保存
                    </n-button>
                    <n-button secondary @click="undo" :disabled="!canUndo">
                        <template #icon><n-icon>
                                <ArrowUndoOutline />
                            </n-icon></template>
                        撤销
                    </n-button>
                    <n-button secondary @click="redo" :disabled="!canRedo">
                        <template #icon><n-icon>
                                <ArrowRedoOutline />
                            </n-icon></template>
                        重做
                    </n-button>
                </n-button-group>
            </div>

            <div class="tool-group center">
                <n-space>
                    <n-button-group>
                        <n-button secondary @click="play" v-if="!isPlaying">
                            <template #icon><n-icon>
                                    <PlayOutline />
                                </n-icon></template>
                            播放
                        </n-button>
                        <n-button secondary @click="pause" v-else>
                            <template #icon><n-icon>
                                    <PauseOutline />
                                </n-icon></template>
                            暂停
                        </n-button>
                        <n-button secondary @click="stop">
                            <template #icon><n-icon>
                                    <StopOutline />
                                </n-icon></template>
                            停止
                        </n-button>
                    </n-button-group>

                    <n-input-number v-model:value="currentTime" :min="0" :max="totalDuration" style="width: 120px" />

                    <n-tooltip trigger="hover">
                        <template #trigger>
                            <span class="time-display">{{ formatTime(currentTime) }} / {{ formatTime(totalDuration)
                                }}</span>
                        </template>
                        当前时间 / 总时长
                    </n-tooltip>
                </n-space>
            </div>

            <div class="tool-group right">
                <n-button type="primary" @click="exportProject">
                    <template #icon><n-icon>
                            <ShareOutline />
                        </n-icon></template>
                    导出
                </n-button>
            </div>
        </div>

        <div class="editor-main">
            <div class="sidebar-left">
                <div class="assets-panel">
                    <div class="panel-header">
                        <span>素材库</span>
                        <n-button quaternary circle size="small">
                            <template #icon><n-icon>
                                    <FolderOpenOutline />
                                </n-icon></template>
                        </n-button>
                    </div>
                    <n-tabs type="line">
                        <n-tab-pane name="characters" tab="角色">
                            <n-scrollbar style="max-height: 400px" :x-scrollable="false">
                                <div class="assets-grid">
                                    <n-empty v-if="assets.characters.length === 0" description="暂无角色" />
                                    <div v-else class="asset-item" v-for="asset in assets.characters" :key="asset.id"
                                        @dragstart="handleAssetDragStart($event, asset)" draggable="true">
                                        <div class="asset-preview">
                                            <img :src="asset.thumbnail" :alt="asset.name">
                                        </div>
                                        <div class="asset-name">{{ asset.name }}</div>
                                    </div>
                                </div>
                            </n-scrollbar>
                        </n-tab-pane>
                        <n-tab-pane name="scenes" tab="场景">
                            <n-scrollbar style="max-height: 400px" :x-scrollable="false">
                                <div class="assets-grid">
                                    <n-empty v-if="assets.scenes.length === 0" description="暂无场景" />
                                    <div v-else class="asset-item" v-for="asset in assets.scenes" :key="asset.id"
                                        @dragstart="handleAssetDragStart($event, asset)" draggable="true">
                                        <div class="asset-preview">
                                            <img :src="asset.thumbnail" :alt="asset.name">
                                        </div>
                                        <div class="asset-name">{{ asset.name }}</div>
                                    </div>
                                </div>
                            </n-scrollbar>
                        </n-tab-pane>
                        <n-tab-pane name="props" tab="道具">
                            <n-scrollbar style="max-height: 400px" :x-scrollable="false">
                                <div class="assets-grid">
                                    <n-empty v-if="assets.props.length === 0" description="暂无道具" />
                                    <div v-else class="asset-item" v-for="asset in assets.props" :key="asset.id"
                                        @dragstart="handleAssetDragStart($event, asset)" draggable="true">
                                        <div class="asset-preview">
                                            <img :src="asset.thumbnail" :alt="asset.name">
                                        </div>
                                        <div class="asset-name">{{ asset.name }}</div>
                                    </div>
                                </div>
                            </n-scrollbar>
                        </n-tab-pane>
                        <n-tab-pane name="effects" tab="特效">
                            <n-scrollbar style="max-height: 400px" :x-scrollable="false">
                                <div class="assets-grid">
                                    <n-empty v-if="assets.effects.length === 0" description="暂无特效" />
                                    <div v-else class="asset-item" v-for="asset in assets.effects" :key="asset.id"
                                        @dragstart="handleAssetDragStart($event, asset)" draggable="true">
                                        <div class="asset-preview">
                                            <img :src="asset.thumbnail" :alt="asset.name">
                                        </div>
                                        <div class="asset-name">{{ asset.name }}</div>
                                    </div>
                                </div>
                            </n-scrollbar>
                        </n-tab-pane>
                    </n-tabs>
                </div>
                <div class="sidebar-left-resizer"></div>
            </div>

            <div class="editor-canvas">
                <div class="canvas-container">
                    <canvas ref="canvas" width="800" height="600"></canvas>
                    <div class="canvas-placeholder" v-if="isCanvasEmpty">
                        <n-icon size="48" color="#ccc">
                            <ImagesOutline />
                        </n-icon>
                        <p>从左侧拖拽素材到此处开始创作</p>
                    </div>
                </div>
            </div>

            <div class="sidebar-right">
                <div class="sidebar-right-resizer"></div>
                <n-tabs type="segment">
                    <n-tab-pane name="properties" tab="属性">
                        <div class="properties-panel">
                            <div v-if="!selectedLayer">
                                <n-empty description="请选择一个图层" />
                            </div>
                            <div v-else>
                                <n-form label-placement="left" label-width="80">
                                    <n-form-item label="名称">
                                        <n-input v-model:value="selectedLayer.name" />
                                    </n-form-item>
                                    <n-form-item label="位置">
                                        <n-input-group>
                                            <n-input-number v-model:value="selectedLayer.position.x" :step="1"
                                                placeholder="X" style="width: 50%" />
                                            <n-input-number v-model:value="selectedLayer.position.y" :step="1"
                                                placeholder="Y" style="width: 50%" />
                                        </n-input-group>
                                    </n-form-item>
                                    <n-form-item label="缩放">
                                        <n-input-group>
                                            <n-input-number v-model:value="selectedLayer.scale.x" :step="0.1"
                                                placeholder="X" style="width: 50%" />
                                            <n-input-number v-model:value="selectedLayer.scale.y" :step="0.1"
                                                placeholder="Y" style="width: 50%" />
                                        </n-input-group>
                                    </n-form-item>
                                    <n-form-item label="旋转">
                                        <n-input-number v-model:value="selectedLayer.rotation" :step="1" />
                                    </n-form-item>
                                    <n-form-item label="不透明度">
                                        <n-slider v-model:value="selectedLayer.opacity" :step="1" :min="0" :max="100" />
                                    </n-form-item>
                                    <n-form-item label="可见性">
                                        <n-switch v-model:value="selectedLayer.visible" />
                                    </n-form-item>
                                </n-form>
                            </div>
                        </div>
                    </n-tab-pane>
                    <n-tab-pane name="animations" tab="动画">
                        <n-empty description="暂无动画" />
                    </n-tab-pane>
                </n-tabs>
            </div>
        </div>

        <div class="editor-timeline">
            <div class="timeline-tools">
                <n-button-group>
                    <n-button secondary size="small" @click="addKeyframe">
                        <template #icon><n-icon>
                                <AddOutline />
                            </n-icon></template>
                        添加关键帧
                    </n-button>
                    <n-button secondary size="small" @click="deleteKeyframe" :disabled="!selectedKeyframe">
                        <template #icon><n-icon>
                                <TrashOutline />
                            </n-icon></template>
                        删除关键帧
                    </n-button>
                    <n-button secondary size="small" @click="addTrack">
                        <template #icon><n-icon>
                                <AddCircleOutline />
                            </n-icon></template>
                        添加轨道
                    </n-button>
                    <n-button secondary size="small" @click="deleteTrack" :disabled="!selectedTrack">
                        <template #icon><n-icon>
                                <RemoveCircleOutline />
                            </n-icon></template>
                        删除轨道
                    </n-button>
                </n-button-group>

                <n-select v-model:value="timelineZoom" :options="zoomOptions" size="small" style="width: 120px" />
            </div>

            <div class="timeline-container">
                <div class="timeline-sidebar" :style="{ width: `${timelineSidebarWidth}px` }">
                    <div class="timeline-sidebar-resizer"
                        @mousedown="startDrag($event, 'resize-timeline-sidebar', '', timelineSidebarWidth)"></div>
                    <div class="timeline-track-header">
                        <span>轨道</span>
                        <n-dropdown :options="trackSortOptions" @select="handleTrackSortSelect">
                            <n-button quaternary circle size="tiny">
                                <template #icon><n-icon>
                                        <MenuOutline />
                                    </n-icon></template>
                            </n-button>
                        </n-dropdown>
                    </div>

                    <div class="timeline-tracks">
                        <div v-for="track in tracks" :key="track.id" class="timeline-track"
                            :class="{ 'selected': selectedTrack?.id === track.id }" @click="selectTrack(track, $event)">
                            <div class="track-controls">
                                <n-tooltip trigger="hover" placement="top">
                                    <template #trigger>
                                        <n-button quaternary circle size="tiny"
                                            @click.stop="toggleTrackVisibility(track)">
                                            <template #icon><n-icon size="14">
                                                    <component :is="track.visible ? EyeOutline : EyeOffOutline" />
                                                </n-icon></template>
                                        </n-button>
                                    </template>
                                    {{ track.visible ? '隐藏轨道' : '显示轨道' }}
                                </n-tooltip>
                                <n-tooltip trigger="hover" placement="top">
                                    <template #trigger>
                                        <n-button quaternary circle size="tiny" @click.stop="toggleTrackLock(track)">
                                            <template #icon><n-icon size="14">
                                                    <component
                                                        :is="track.locked ? LockClosedOutline : LockOpenOutline" />
                                                </n-icon></template>
                                        </n-button>
                                    </template>
                                    {{ track.locked ? '解锁轨道' : '锁定轨道' }}
                                </n-tooltip>
                            </div>
                            <span class="track-name">{{ track.name }}</span>
                            <n-dropdown trigger="click" :options="trackOptions" @select="handleTrackOptionSelect">
                                <n-button quaternary circle size="tiny" @click.stop>
                                    <template #icon><n-icon size="14">
                                            <EllipsisVerticalOutline />
                                        </n-icon></template>
                                </n-button>
                            </n-dropdown>
                        </div>
                    </div>
                </div>

                <div class="timeline-content">
                    <div class="timeline-ruler" @click="handleRulerClick">
                        <div class="timeline-ruler-inner" :style="{ width: `${totalDuration * timelineZoom}px` }">
                            <div v-for="tick in timelineTicks" :key="tick" class="timeline-tick"
                                :style="{ left: `${tick * timelineZoom / 10}px` }">
                                <span v-if="tick % 10 === 0" class="tick-label">{{ tick / 10 }}s</span>
                            </div>
                        </div>
                    </div>

                    <div class="timeline-current-indicator"
                        :style="{ transform: `translateX(${currentTime * timelineZoom}px)` }"></div>

                    <div class="timeline-tracks-content">
                        <div v-for="track in tracks" :key="track.id" class="timeline-track-content"
                            :class="{ 'selected': selectedTrack?.id === track.id, 'locked': track.locked, 'hidden': !track.visible }"
                            :style="{ width: `${totalDuration * timelineZoom + 20}px` }">
                            <div v-for="keyframe in track.keyframes" :key="keyframe.id" class="keyframe"
                                :style="{ left: `${keyframe.time * timelineZoom}px` }"
                                :class="{ 'selected': selectedKeyframe?.id === keyframe.id }" :data-id="keyframe.id"
                                @click.stop="selectKeyframe(keyframe)"></div>
                            <div v-if="track.clips && track.clips.length > 0" v-for="clip in track.clips" :key="clip.id"
                                class="clip" :style="{
                                    left: `${clip.startTime * timelineZoom}px`,
                                    width: `${(clip.endTime - clip.startTime) * timelineZoom}px`,
                                    maxWidth: `${totalDuration * timelineZoom - clip.startTime * timelineZoom}px`
                                }"
                                @mousedown.stop="startDrag($event, 'clip', clip.id, { startTime: clip.startTime, endTime: clip.endTime })">
                                <div class="clip-handle left"
                                    @mousedown.stop="startDrag($event, 'clip-left', clip.id, clip.startTime)"></div>
                                <div class="clip-label">{{ clip.name }}</div>
                                <div class="clip-handle right"
                                    @mousedown.stop="startDrag($event, 'clip-right', clip.id, clip.endTime)"></div>
                            </div>
                            <div class="timeline-track-drop-area" @click.stop="selectTrack(track, $event)"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="timeline-resizer" @mousedown="startDrag($event, 'resize-timeline', '', timelineHeight)"></div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue'
import { throttle, debounce, rafThrottle } from '../../utils/tools'
import {
    NButton,
    NButtonGroup,
    NIcon,
    NSpace,
    NInputNumber,
    NTooltip,
    NTabs,
    NTabPane,
    NEmpty,
    NCheckbox,
    NForm,
    NFormItem,
    NInput,
    NInputGroup,
    NSlider,
    NSwitch,
    NSelect,
    NScrollbar,
    NDropdown,
    NBadge
} from 'naive-ui'
import {
    SaveOutline,
    ArrowUndoOutline,
    ArrowRedoOutline,
    PlayOutline,
    PauseOutline,
    StopOutline,
    ShareOutline,
    AddOutline,
    TrashOutline,
    LockOpenOutline,
    LockClosedOutline,
    ImagesOutline,
    FolderOpenOutline,
    EyeOutline,
    EyeOffOutline,
    MenuOutline,
    AddCircleOutline,
    RemoveCircleOutline,
    EllipsisVerticalOutline,
    NotificationsOutline
} from '@vicons/ionicons5'

// 模拟数据
const currentTime = ref(0)
const totalDuration = ref(300) // 5分钟，单位秒
const isPlaying = ref(false)
const canUndo = ref(false)
const canRedo = ref(false)
const isCanvasEmpty = ref(true)
const notificationCount = ref(2)

const canvas = ref<HTMLCanvasElement | null>(null)

const timelineZoom = ref(10) // 每秒占用的像素数
const zoomOptions = [
    { label: '25%', value: 2.5 },
    { label: '50%', value: 5 },
    { label: '100%', value: 10 },
    { label: '200%', value: 20 },
    { label: '400%', value: 40 }
]

// 时间轴刻度
const timelineTicks = computed(() => {
    const ticks: number[] = []
    for (let i = 0; i <= totalDuration.value * 10; i++) {
        ticks.push(i)
    }
    return ticks
})

// 拖动状态
const dragState = reactive({
    isDragging: false,
    type: '', // 'timeline', 'canvas', 'keyframe', 'layer', 'resize'
    startX: 0,
    startY: 0,
    targetId: '',
    originalValue: null
})

// 图层数据
const layers = ref([
    {
        id: '1',
        name: '背景图层',
        visible: true,
        locked: false,
        type: 'image',
        position: { x: 400, y: 300 },
        scale: { x: 1, y: 1 },
        rotation: 0,
        opacity: 100
    },
    {
        id: '2',
        name: '角色图层',
        visible: true,
        locked: false,
        type: 'character',
        position: { x: 400, y: 300 },
        scale: { x: 1, y: 1 },
        rotation: 0,
        opacity: 100
    }
])

// 轨道数据
const tracks = ref([
    {
        id: '1',
        name: '背景图层',
        type: 'scene',
        layerId: '1',
        visible: true,
        locked: false,
        keyframes: [
            { id: '1', time: 0, value: { opacity: 100 } },
            { id: '2', time: 60, value: { opacity: 50 } },
            { id: '3', time: 120, value: { opacity: 100 } }
        ],
        clips: [
            { id: 'clip1', name: '场景1', startTime: 0, endTime: 120 }
        ]
    },
    {
        id: '2',
        name: '角色图层',
        type: 'character',
        layerId: '2',
        visible: true,
        locked: false,
        keyframes: [
            { id: '4', time: 0, value: { position: { x: 200, y: 300 } } },
            { id: '5', time: 90, value: { position: { x: 600, y: 300 } } },
            { id: '6', time: 180, value: { position: { x: 400, y: 300 } } }
        ],
        clips: [
            { id: 'clip2', name: '人物1', startTime: 0, endTime: 180 }
        ]
    },
    {
        id: '3',
        name: '特效图层',
        type: 'effect',
        layerId: '3',
        visible: true,
        locked: false,
        keyframes: [
            { id: '7', time: 30, value: { opacity: 0 } },
            { id: '8', time: 60, value: { opacity: 100 } },
            { id: '9', time: 90, value: { opacity: 0 } }
        ],
        clips: [
            { id: 'clip3', name: '特效1', startTime: 30, endTime: 90 }
        ]
    }
])

// 素材数据
const assets = reactive({
    characters: [
        { id: '1', name: '人物1', type: 'character', thumbnail: 'https://placeholder.pics/svg/80x120/DEDEDE/555555/角色1' },
        { id: '2', name: '人物2', type: 'character', thumbnail: 'https://placeholder.pics/svg/80x120/DEDEDE/555555/角色2' }
    ],
    scenes: [
        { id: '3', name: '场景1', type: 'scene', thumbnail: 'https://placeholder.pics/svg/120x80/E0E0FF/555555/场景1' }
    ],
    props: [
        { id: '4', name: '道具1', type: 'prop', thumbnail: 'https://placeholder.pics/svg/80x80/FFE0E0/555555/道具1' }
    ],
    effects: [
        { id: '5', name: '特效1', type: 'effect', thumbnail: 'https://placeholder.pics/svg/80x80/E0FFE0/555555/特效1' },
        { id: '6', name: '特效2', type: 'effect', thumbnail: 'https://placeholder.pics/svg/80x80/E0FFE0/555555/特效2' }
    ]
})

// 选中状态
const selectedLayer = ref(layers.value[0])
const selectedTrack = ref(tracks.value[0])
const selectedKeyframe = ref<{ id: string; time: number; value: any } | null>(null)

// 面板尺寸
const leftSidebarWidth = ref(280)
const rightSidebarWidth = ref(280)
const timelineHeight = ref(200)
const timelineSidebarWidth = ref(160)

// 轨道排序选项
const trackSortOptions = [
    {
        label: '排序方式',
        key: 'sort',
        children: [
            {
                label: '按名称排序',
                key: 'name'
            },
            {
                label: '按类型排序',
                key: 'type'
            },
            {
                label: '按创建时间排序',
                key: 'created'
            }
        ]
    }
]

// 轨道右键菜单选项
const trackOptions = [
    {
        label: '重命名',
        key: 'rename'
    },
    {
        label: '复制轨道',
        key: 'duplicate'
    },
    {
        label: '删除轨道',
        key: 'delete'
    },
    {
        type: 'divider',
        key: 'd1'
    },
    {
        label: '轨道设置',
        key: 'settings'
    }
]

// 方法
const save = () => {
    console.log('保存项目')
}

const undo = () => {
    console.log('撤销')
}

const redo = () => {
    console.log('重做')
}

const play = () => {
    isPlaying.value = true
    console.log('播放')
}

const pause = () => {
    isPlaying.value = false
    console.log('暂停')
}

const stop = () => {
    isPlaying.value = false
    currentTime.value = 0
    console.log('停止')
}

const exportProject = () => {
    console.log('导出项目')
}

const selectLayer = (layer: any) => {
    selectedLayer.value = layer
}

const lockLayer = (layer: any) => {
    layer.locked = !layer.locked
}

const selectTrack = (track: any, event?: MouseEvent) => {
    // 如果有事件对象，阻止事件冒泡
    if (event) {
        event.stopPropagation()
        event.preventDefault()
    }

    // 实现切换逻辑：点击未选中的轨道选中，点击已选中的轨道取消选择
    if (selectedTrack.value && selectedTrack.value.id === track.id) {
        // 如果点击的是已选中的轨道，则取消选择
        selectedTrack.value = null
    } else {
        // 如果点击的是未选中的轨道，则选中它
        selectedTrack.value = track
    }
}

const selectKeyframe = (keyframe: any) => {
    selectedKeyframe.value = keyframe
}

// 格式化时间
const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 更新拖动状态的视觉反馈
const updateResizerActiveState = () => {
    // 清除所有resizer的激活状态
    const allResizers = document.querySelectorAll('.sidebar-left-resizer, .sidebar-right-resizer, .timeline-resizer, .timeline-sidebar-resizer')
    allResizers.forEach(resizer => {
        (resizer as HTMLElement).classList.remove('active')
    })

    // 根据当前拖动类型添加激活状态
    if (dragState.isDragging) {
        let selector = '';
        switch (dragState.type) {
            case 'resize-left-sidebar':
                selector = '.sidebar-left-resizer';
                break;
            case 'resize-right-sidebar':
                selector = '.sidebar-right-resizer';
                break;
            case 'resize-timeline':
                selector = '.timeline-resizer';
                break;
            case 'resize-timeline-sidebar':
                selector = '.timeline-sidebar-resizer';
                break;
        }

        if (selector) {
            const resizer = document.querySelector(selector)
            if (resizer) (resizer as HTMLElement).classList.add('active')
        }
    }
}

// 使用RAF节流处理视觉反馈
const updateResizerActiveStateThrottled = rafThrottle(updateResizerActiveState);

// 拖动处理函数
const handleDrag = (e: MouseEvent) => {
    // 使用节流函数处理拖动
    handleDragThrottled(e);
}

// 使用节流处理拖动函数
const handleDragThrottled = throttle((e: MouseEvent) => {
    if (!dragState.isDragging) return

    const deltaX = e.clientX - dragState.startX
    const deltaY = e.clientY - dragState.startY

    switch (dragState.type) {
        case 'timeline-cursor':
            // 拖动时间线指示器
            if (dragState.originalValue == null) return
            const timelineNewTime = Math.max(0, Math.min(totalDuration.value,
                dragState.originalValue + deltaX / timelineZoom.value))
            currentTime.value = timelineNewTime
            break

        case 'keyframe':
            // 拖动关键帧
            if (!dragState.targetId) return
            const track = tracks.value.find(t =>
                t.keyframes.some(k => k.id === dragState.targetId))
            if (!track) return
            const keyframe = track.keyframes.find(k => k.id === dragState.targetId)
            if (!keyframe) return
            if (dragState.originalValue == null) return
            const keyframeNewTime = Math.max(0, Math.min(totalDuration.value,
                dragState.originalValue + deltaX / timelineZoom.value))
            keyframe.time = keyframeNewTime
            break

        case 'canvas-element':
            // 拖动画布元素
            if (!selectedLayer.value || selectedLayer.value.locked) return
            if (dragState.originalValue == null) return
            // 确保originalValue有正确的类型
            const originalPos = dragState.originalValue as { x: number, y: number }
            selectedLayer.value.position.x = originalPos.x + deltaX
            selectedLayer.value.position.y = originalPos.y + deltaY
            updateCanvasThrottled()
            break

        case 'resize-left-sidebar':
            // 调整左侧边栏宽度
            if (dragState.originalValue == null) return
            leftSidebarWidth.value = Math.max(200, Math.min(400, dragState.originalValue + deltaX))
            // 直接应用样式而不是等待watch
            applyLeftSidebarWidth()
            break

        case 'resize-right-sidebar':
            // 调整右侧边栏宽度
            if (dragState.originalValue == null) return
            rightSidebarWidth.value = Math.max(200, Math.min(400, dragState.originalValue - deltaX))
            // 直接应用样式而不是等待watch
            applyRightSidebarWidth()
            break

        case 'resize-timeline':
            // 调整时间轴高度
            if (dragState.originalValue == null) return
            timelineHeight.value = Math.max(150, Math.min(400, dragState.originalValue - deltaY))
            // 直接应用样式而不是等待watch
            applyTimelineHeight()
            break

        case 'resize-timeline-sidebar':
            // 调整时间轴侧边栏宽度
            if (dragState.originalValue == null) return
            timelineSidebarWidth.value = Math.max(120, Math.min(300, dragState.originalValue + deltaX))
            break

        case 'track-order':
            // 调整轨道顺序
            // 这里需要更复杂的实现，简化版本
            if (Math.abs(deltaY) > 15) {
                // 实际项目中应该实现平滑的拖动排序
                console.log('重新排序轨道', dragState.targetId)
            }
            break

        case 'clip':
            // 拖动片段
            if (!dragState.targetId || !dragState.originalValue) return
            const clipTrack = tracks.value.find(t =>
                t.clips && t.clips.some(c => c.id === dragState.targetId))
            if (!clipTrack || clipTrack.locked) return
            const clip = clipTrack.clips.find(c => c.id === dragState.targetId)
            if (!clip) return

            const originalTimes = dragState.originalValue as { startTime: number, endTime: number }
            const clipDuration = originalTimes.endTime - originalTimes.startTime
            let newStartTime = Math.max(0, originalTimes.startTime + deltaX / timelineZoom.value)

            // 确保不超出总时长
            if (newStartTime + clipDuration > totalDuration.value) {
                newStartTime = totalDuration.value - clipDuration
            }

            clip.startTime = newStartTime
            clip.endTime = newStartTime + clipDuration
            break

        case 'clip-left':
            // 调整片段左侧（开始时间）
            if (!dragState.targetId || dragState.originalValue == null) return
            const leftClipTrack = tracks.value.find(t =>
                t.clips && t.clips.some(c => c.id === dragState.targetId))
            if (!leftClipTrack || leftClipTrack.locked) return
            const leftClip = leftClipTrack.clips.find(c => c.id === dragState.targetId)
            if (!leftClip) return

            const newStart = Math.max(0, Math.min(leftClip.endTime - 1,
                dragState.originalValue + deltaX / timelineZoom.value))
            leftClip.startTime = newStart
            break

        case 'clip-right':
            // 调整片段右侧（结束时间）
            if (!dragState.targetId || dragState.originalValue == null) return
            const rightClipTrack = tracks.value.find(t =>
                t.clips && t.clips.some(c => c.id === dragState.targetId))
            if (!rightClipTrack || rightClipTrack.locked) return
            const rightClip = rightClipTrack.clips.find(c => c.id === dragState.targetId)
            if (!rightClip) return

            const newEnd = Math.max(rightClip.startTime + 1, Math.min(totalDuration.value,
                dragState.originalValue + deltaX / timelineZoom.value))
            rightClip.endTime = newEnd
            break
    }
}, 16); // 约60fps的更新频率

// 拖动结束
const endDrag = () => {
    dragState.isDragging = false
    document.removeEventListener('mousemove', handleDrag)
    document.removeEventListener('mouseup', endDrag)

    // 清除拖动结束时的视觉反馈
    updateResizerActiveState()
}

// 拖动相关方法
const startDrag = (e: MouseEvent, type: string, id: string = '', originalValue: any = null) => {
    if (e.button !== 0) return // 只处理左键点击

    dragState.isDragging = true
    dragState.type = type
    dragState.startX = e.clientX
    dragState.startY = e.clientY
    dragState.targetId = id
    dragState.originalValue = originalValue

    // 立即更新视觉反馈
    updateResizerActiveState()

    document.addEventListener('mousemove', handleDrag)
    document.addEventListener('mouseup', endDrag)

    e.preventDefault()
}

// 直接应用样式函数，避免通过watch触发
const applyLeftSidebarWidth = () => {
    const leftSidebar = document.querySelector('.sidebar-left')
    if (leftSidebar) {
        (leftSidebar as HTMLElement).style.width = `${leftSidebarWidth.value}px`
    }
}

const applyRightSidebarWidth = () => {
    const rightSidebar = document.querySelector('.sidebar-right')
    if (rightSidebar) {
        (rightSidebar as HTMLElement).style.width = `${rightSidebarWidth.value}px`
    }
}

const applyTimelineHeight = () => {
    const timeline = document.querySelector('.editor-timeline')
    if (timeline) {
        (timeline as HTMLElement).style.height = `${timelineHeight.value}px`
    }
}

// 更新时间线指示器位置
const updateTimelineIndicator = () => {
    const indicator = document.querySelector('.timeline-current-indicator')
    if (indicator) {
        // 使用transform代替left，获得更好的性能
        (indicator as HTMLElement).style.transform = `translateX(${currentTime.value * timelineZoom.value}px)`
    }
}

// 更新画布
const updateCanvas = () => {
    if (!canvas.value) return

    const ctx = canvas.value.getContext('2d')
    if (!ctx) return

    // 清空画布
    ctx.fillStyle = '#f0f0f0'
    ctx.fillRect(0, 0, canvas.value.width, canvas.value.height)

    // 绘制中心十字线
    ctx.strokeStyle = '#ccc'
    ctx.lineWidth = 1
    ctx.beginPath()
    ctx.moveTo(canvas.value.width / 2, 0)
    ctx.lineTo(canvas.value.width / 2, canvas.value.height)
    ctx.moveTo(0, canvas.value.height / 2)
    ctx.lineTo(canvas.value.width, canvas.value.height / 2)
    ctx.stroke()

    // 绘制图层（简化版）
    layers.value.forEach(layer => {
        if (!layer.visible) return

        ctx.save()
        ctx.translate(layer.position.x, layer.position.y)
        ctx.rotate(layer.rotation * Math.PI / 180)
        ctx.scale(layer.scale.x, layer.scale.y)
        ctx.globalAlpha = layer.opacity / 100

        // 绘制占位符
        ctx.fillStyle = layer.id === '1' ? '#e0e0ff' : '#ffe0e0'
        ctx.fillRect(-50, -50, 100, 100)
        ctx.fillStyle = '#000'
        ctx.textAlign = 'center'
        ctx.textBaseline = 'middle'
        ctx.fillText(layer.name, 0, 0)

        ctx.restore()
    })
}

// 使用RAF节流优化画布更新
const updateCanvasThrottled = rafThrottle(updateCanvas);

// 使用RAF节流优化时间线指示器位置更新
const updateTimelineIndicatorThrottled = rafThrottle(updateTimelineIndicator);

// 拖放素材到画布
const handleAssetDragStart = (e: DragEvent, asset: any) => {
    if (!e.dataTransfer) return
    e.dataTransfer.setData('application/json', JSON.stringify(asset))
    e.dataTransfer.effectAllowed = 'copy'
}

const handleCanvasDragOver = (e: DragEvent) => {
    if (!e.dataTransfer) return
    e.preventDefault()
    e.dataTransfer.dropEffect = 'copy'
}

const handleCanvasDrop = (e: DragEvent) => {
    e.preventDefault()
    if (!e.dataTransfer) return

    const data = e.dataTransfer.getData('application/json')
    if (!data) return

    try {
        const asset = JSON.parse(data)
        const rect = canvas.value?.getBoundingClientRect()
        if (!rect) return

        // 创建新图层
        const newLayer = {
            id: `layer-${Date.now()}`,
            name: asset.name,
            visible: true,
            locked: false,
            type: asset.type || 'image',
            position: {
                x: e.clientX - rect.left,
                y: e.clientY - rect.top
            },
            scale: { x: 1, y: 1 },
            rotation: 0,
            opacity: 100,
            assetId: asset.id
        }

        layers.value.push(newLayer)
        isCanvasEmpty.value = false
        selectedLayer.value = newLayer
        updateCanvas()

        // 创建对应的轨道
        const newTrack = {
            id: `track-${Date.now()}`,
            name: asset.name,
            type: asset.type || 'image',
            layerId: newLayer.id,
            keyframes: [
                {
                    id: `keyframe-${Date.now()}`,
                    time: currentTime.value,
                    value: { position: { ...newLayer.position } }
                }
            ]
        }

        tracks.value.push(newTrack)

    } catch (error) {
        console.error('无法解析拖放的数据', error)
    }
}

// 轨道排序处理
const handleTrackSortSelect = (key: string) => {
    switch (key) {
        case 'name':
            tracks.value.sort((a, b) => a.name.localeCompare(b.name))
            break
        case 'type':
            tracks.value.sort((a, b) => a.type.localeCompare(b.type))
            break
        case 'created':
            // 假设ID中包含创建时间信息
            tracks.value.sort((a, b) => a.id.localeCompare(b.id))
            break
    }
}

// 轨道选项处理
const handleTrackOptionSelect = (key: string) => {
    if (!selectedTrack.value) return

    switch (key) {
        case 'rename':
            // 实现重命名逻辑
            window.$dialog?.warning({
                title: '重命名轨道',
                content: '请输入新的轨道名称',
                positiveText: '确定',
                negativeText: '取消',
                onPositiveClick: () => {
                    // 实现重命名逻辑
                }
            })
            break
        case 'duplicate':
            duplicateTrack(selectedTrack.value)
            break
        case 'delete':
            deleteTrack()
            break
        case 'settings':
            // 实现轨道设置逻辑
            break
    }
}

// 添加轨道
const addTrack = () => {
    const newTrack = {
        id: `track-${Date.now()}`,
        name: `新轨道 ${tracks.value.length + 1}`,
        type: 'generic',
        layerId: `layer-${Date.now()}`,
        visible: true,
        locked: false,
        keyframes: [],
        clips: []
    }

    tracks.value.push(newTrack)
    selectTrack(newTrack)
}

// 删除轨道
const deleteTrack = () => {
    if (!selectedTrack.value) return

    window.$dialog?.warning({
        title: '删除轨道',
        content: `确定要删除轨道 "${selectedTrack.value.name}" 吗？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
            const index = tracks.value.findIndex(t => t.id === selectedTrack.value?.id)
            if (index !== -1) {
                tracks.value.splice(index, 1)
                selectedTrack.value = tracks.value.length > 0 ? tracks.value[0] : null
            }
        }
    })
}

// 复制轨道
const duplicateTrack = (track: any) => {
    const newTrack = JSON.parse(JSON.stringify(track))
    newTrack.id = `track-${Date.now()}`
    newTrack.name = `${track.name} 副本`

    // 生成新的keyframe IDs
    if (newTrack.keyframes) {
        newTrack.keyframes.forEach((kf: any) => {
            kf.id = `keyframe-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
        })
    }

    // 生成新的clip IDs
    if (newTrack.clips) {
        newTrack.clips.forEach((clip: any) => {
            clip.id = `clip-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
        })
    }

    tracks.value.push(newTrack)
    selectTrack(newTrack)
}

// 切换轨道可见性
const toggleTrackVisibility = (track: any) => {
    
    track.visible = !track.visible

    // 同时更新关联图层的可见性
    const layer = layers.value.find(l => l.id === track.layerId)
    if (layer) {
        layer.visible = track.visible
        updateCanvas()
    }
}

// 切换轨道锁定状态
const toggleTrackLock = (track: any) => {
    track.locked = !track.locked

    // 同时更新关联图层的锁定状态
    const layer = layers.value.find(l => l.id === track.layerId)
    if (layer) {
        layer.locked = track.locked
    }
}

// 添加关键帧
const addKeyframe = () => {
    if (!selectedTrack.value) return

    // 检查当前时间是否已有关键帧
    const existingKeyframe = selectedTrack.value.keyframes.find(k => k.time === currentTime.value)
    if (existingKeyframe) {
        window.$message?.warning('当前时间点已存在关键帧')
        return
    }

    // 查找关联的图层
    const layer = layers.value.find(l => l.id === selectedTrack.value?.layerId)
    if (!layer) return

    // 创建新关键帧
    const newKeyframe = {
        id: `keyframe-${Date.now()}`,
        time: currentTime.value,
        value: {
            position: { ...layer.position },
            scale: { ...layer.scale },
            rotation: layer.rotation,
            opacity: layer.opacity
        }
    }

    selectedTrack.value.keyframes.push(newKeyframe)
    selectKeyframe(newKeyframe)
}

// 删除关键帧
const deleteKeyframe = () => {
    if (!selectedKeyframe.value || !selectedTrack.value) return

    const index = selectedTrack.value.keyframes.findIndex(k => k.id === selectedKeyframe.value?.id)
    if (index !== -1) {
        selectedTrack.value.keyframes.splice(index, 1)
        selectedKeyframe.value = null
    }
}

// 处理时间尺点击
const handleRulerClick = (e: MouseEvent) => {
    // 计算点击位置对应的时间
    const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
    const scrollLeft = (e.currentTarget.parentElement as HTMLElement).scrollLeft
    const x = e.clientX - rect.left + scrollLeft
    const clickTime = x / timelineZoom.value

    // 设置当前时间
    currentTime.value = Math.max(0, Math.min(totalDuration.value, clickTime))
}

// 处理轨道内容点击
const handleTrackContentClick = (e: MouseEvent, track: any) => {
    if (track.locked) return

    // 只选择轨道，不改变时间
    selectTrack(track)
}

onMounted(() => {
    // 初始化画布
    updateCanvas()

    // 初始化时间线指示器位置
    updateTimelineIndicator()

    // 初始化侧边栏宽度
    applyLeftSidebarWidth()
    applyRightSidebarWidth()

    // 初始化时间轴高度
    applyTimelineHeight()

    // 添加时间线指示器拖动功能
    const timelineIndicator = document.querySelector('.timeline-current-indicator')
    if (timelineIndicator) {
        timelineIndicator.addEventListener('mousedown', (e: Event) => {
            // 使用类型断言，确保事件有MouseEvent所需的属性
            const mouseEvent = e as unknown as MouseEvent
            startDrag(mouseEvent, 'timeline-cursor', '', currentTime.value)
        })
    }

    // 添加面板大小调整功能
    const leftResizer = document.querySelector('.sidebar-left-resizer')
    if (leftResizer) {
        leftResizer.addEventListener('mousedown', (e: Event) => {
            // 使用类型断言，确保事件有MouseEvent所需的属性
            const mouseEvent = e as unknown as MouseEvent
            startDrag(mouseEvent, 'resize-left-sidebar', '', leftSidebarWidth.value)
        })
    }

    const rightResizer = document.querySelector('.sidebar-right-resizer')
    if (rightResizer) {
        rightResizer.addEventListener('mousedown', (e: Event) => {
            // 使用类型断言，确保事件有MouseEvent所需的属性
            const mouseEvent = e as unknown as MouseEvent
            startDrag(mouseEvent, 'resize-right-sidebar', '', rightSidebarWidth.value)
        })
    }

    const timelineResizer = document.querySelector('.timeline-resizer')
    if (timelineResizer) {
        timelineResizer.addEventListener('mousedown', (e: Event) => {
            // 使用类型断言，确保事件有MouseEvent所需的属性
            const mouseEvent = e as unknown as MouseEvent
            startDrag(mouseEvent, 'resize-timeline', '', timelineHeight.value)
        })
    }

    // 添加时间线侧边栏大小调整功能
    const timelineSidebarResizer = document.querySelector('.timeline-sidebar-resizer')
    if (timelineSidebarResizer) {
        timelineSidebarResizer.addEventListener('mousedown', (e: Event) => {
            // 使用类型断言，确保事件有MouseEvent所需的属性
            const mouseEvent = e as unknown as MouseEvent
            startDrag(mouseEvent, 'resize-timeline-sidebar', '', timelineSidebarWidth.value)
        })
    }

    // 添加画布元素拖动功能
    if (canvas.value) {
        canvas.value.addEventListener('mousedown', (e: MouseEvent) => {
            // 如果有选中的图层，开始拖动
            if (selectedLayer.value && !selectedLayer.value.locked) {
                startDrag(e, 'canvas-element', selectedLayer.value.id, { ...selectedLayer.value.position })
                canvas.value?.classList.add('dragging')
            }
        })

        // 拖动结束时移除dragging类
        document.addEventListener('mouseup', () => {
            canvas.value?.classList.remove('dragging')
        })
    }

    // 添加关键帧拖动功能
    const setupKeyframeDrag = () => {
        const keyframes = document.querySelectorAll('.keyframe')
        keyframes.forEach(keyframe => {
            keyframe.addEventListener('mousedown', (e: Event) => {
                const mouseEvent = e as unknown as MouseEvent
                mouseEvent.stopPropagation() // 防止冒泡触发track的事件

                // 找到对应的关键帧数据
                const keyframeId = (keyframe as HTMLElement).getAttribute('data-id')
                if (!keyframeId) return

                let foundKeyframe: any = null
                let foundTrack: any = null

                for (const track of tracks.value) {
                    const kf = track.keyframes.find(k => k.id === keyframeId)
                    if (kf) {
                        foundKeyframe = kf
                        foundTrack = track
                        break
                    }
                }

                if (foundKeyframe) {
                    selectKeyframe(foundKeyframe)
                    startDrag(mouseEvent, 'keyframe', keyframeId, foundKeyframe.time)
                }
            })
        })
    }

    // 初始化关键帧拖动，并在tracks变化时重新设置
    setupKeyframeDrag()
    watch(tracks, () => {
        nextTick(() => {
            setupKeyframeDrag()
        })
    }, { deep: true })
})

// 修改监听器，使用防抖减少不必要的更新
watch([currentTime, timelineZoom], debounce(() => {
    updateTimelineIndicatorThrottled();
}, 50), { flush: 'post' });
</script>

<style lang="scss" scoped>
.editor-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    overflow: hidden;

    .editor-toolbar {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 8px 16px;
        background-color: var(--component-background);
        border-bottom: 1px solid var(--border-color-base);

        .tool-group {
            &.center {
                flex: 1;
                display: flex;
                justify-content: center;
            }

            &.right {
                display: flex;
                align-items: center;
                gap: 8px;
            }

            .time-display {
                font-family: monospace;
                font-size: 14px;
                padding: 0 8px;
                line-height: 34px;
                display: inline-block;
            }

            .notification-area {
                position: relative;

                :deep(.n-badge) {
                    .n-badge-sup {
                        transform: translate(50%, -50%);
                    }
                }
            }
        }
    }

    .editor-main {
        display: flex;
        flex: 1;
        overflow: hidden;

        .sidebar-left,
        .sidebar-right {
            position: relative;
            background-color: var(--component-background);
            border-right: 1px solid var(--border-color-base);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .sidebar-left {
            width: 280px;

            .sidebar-left-resizer {
                position: absolute;
                top: 0;
                right: 0px;
                width: 5px;
                height: 100%;
                cursor: col-resize;
                z-index: 10;
                background: transparent;

                &:hover {
                    background: rgba(var(--primary-color-rgb), 0.1);
                }

                &:active,
                &.active {
                    background: #1890ff;
                    /* 明确的蓝色 */
                }
            }
        }

        .sidebar-right {
            width: 280px;
            border-right: none;
            border-left: 1px solid var(--border-color-base);

            .sidebar-right-resizer {
                position: absolute;
                top: 0;
                left: 0px;
                width: 5px;
                height: 100%;
                cursor: col-resize;
                z-index: 10;
                background: transparent;

                &:hover {
                    background: rgba(var(--primary-color-rgb), 0.1);
                }

                &:active,
                &.active {
                    background: #1890ff;
                    /* 明确的蓝色 */
                }
            }
        }

        .editor-canvas {
            flex: 1;
            background-color: var(--body-color);
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;

            .canvas-container {
                position: relative;

                canvas {
                    background-color: #fff;
                    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                    cursor: grab;

                    &.dragging {
                        cursor: grabbing;
                    }
                }

                .canvas-placeholder {
                    position: absolute;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                    pointer-events: none;

                    p {
                        margin-top: 16px;
                        color: #ccc;
                    }
                }

                .canvas-controls {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    pointer-events: none;

                    .control-point {
                        position: absolute;
                        width: 10px;
                        height: 10px;
                        background-color: #fff;
                        border: 1px solid var(--primary-color);
                        pointer-events: auto;

                        &.top-left {
                            top: -5px;
                            left: -5px;
                            cursor: nwse-resize;
                        }

                        &.top-right {
                            top: -5px;
                            right: -5px;
                            cursor: nesw-resize;
                        }

                        &.bottom-left {
                            bottom: -5px;
                            left: -5px;
                            cursor: nesw-resize;
                        }

                        &.bottom-right {
                            bottom: -5px;
                            right: -5px;
                            cursor: nwse-resize;
                        }

                        &.top {
                            top: -5px;
                            left: 50%;
                            margin-left: -5px;
                            cursor: ns-resize;
                        }

                        &.right {
                            top: 50%;
                            right: -5px;
                            margin-top: -5px;
                            cursor: ew-resize;
                        }

                        &.bottom {
                            bottom: -5px;
                            left: 50%;
                            margin-left: -5px;
                            cursor: ns-resize;
                        }

                        &.left {
                            top: 50%;
                            left: -5px;
                            margin-top: -5px;
                            cursor: ew-resize;
                        }

                        &.rotation {
                            top: -25px;
                            left: 50%;
                            margin-left: -5px;
                            cursor: url('data:image/png;base64,...'), auto;
                        }
                    }
                }
            }
        }

        .assets-panel,
        .properties-panel {
            padding: 8px;
            height: 100%;
            display: flex;
            flex-direction: column;

            .panel-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 8px;

                span {
                    font-weight: 500;
                }
            }

            .assets-grid {
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 12px;
                padding: 8px;

                .asset-item {
                    cursor: grab;
                    border-radius: 4px;
                    overflow: hidden;

                    &:hover {
                        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
                    }

                    &:active {
                        cursor: grabbing;
                    }

                    .asset-preview {
                        height: 100px;
                        background-color: #f5f5f5;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        overflow: hidden;

                        img {
                            max-width: 100%;
                            max-height: 100%;
                            object-fit: contain;
                        }
                    }

                    .asset-name {
                        padding: 6px;
                        font-size: 12px;
                        text-align: center;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }
                }
            }
        }
    }

    .editor-timeline {
        position: relative;
        height: 200px;
        background-color: var(--component-background);
        border-top: 1px solid var(--border-color-base);
        display: flex;
        flex-direction: column;

        .timeline-resizer {
            position: absolute;
            top: 0px;
            left: 0;
            right: 0;
            height: 5px;
            cursor: row-resize;
            z-index: 10;
            background: transparent;

            &:hover {
                background: rgba(var(--primary-color-rgb), 0.1);
            }

            &:active,
            &.active {
                background: #1890ff;
                /* 明确的蓝色 */
            }
        }

        .timeline-tools {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px;
            border-bottom: 1px solid var(--border-color-base);
        }

        .timeline-container {
            display: flex;
            flex: 1;
            overflow: hidden;

            .timeline-sidebar {
                width: 160px;
                border-right: 1px solid var(--border-color-base);
                display: flex;
                flex-direction: column;
                position: relative;

                .timeline-sidebar-resizer {
                    position: absolute;
                    top: 0;
                    right: 0;
                    width: 5px;
                    height: 100%;
                    cursor: col-resize;
                    z-index: 10;
                    background: transparent;

                    &:hover {
                        background: rgba(var(--primary-color-rgb), 0.1);
                    }

                    &:active,
                    &.active {
                        background: #1890ff;
                        /* 明确的蓝色 */
                    }
                }

                .timeline-track-header {
                    height: 24px;
                    padding: 0 8px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    background-color: var(--card-color);
                    border-bottom: 1px solid var(--border-color-base);

                    span {
                        font-weight: 500;
                        font-size: 12px;
                    }
                }

                .timeline-tracks {
                    flex: 1;
                    overflow-y: auto;

                    .timeline-track {
                        height: 30px;
                        padding: 0 4px;
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        cursor: grab;

                        &:hover {
                            background-color: var(--item-hover-color);
                        }

                        &:active {
                            cursor: grabbing;
                        }

                        &.selected {
                            background-color: var(--primary-color-pressed) !important;
                            color: white !important;
                            border-left: 3px solid var(--primary-color);
                            box-shadow: inset 0 0 0 1px var(--primary-color);
                        }

                        .track-controls {
                            display: flex;
                            gap: 1px;
                        }

                        .track-name {
                            flex: 1;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            margin: 0 4px;
                            font-size: 12px;
                        }
                    }
                }
            }

            .timeline-content {
                flex: 1;
                display: flex;
                flex-direction: column;
                overflow: auto;
                /* 保持可滚动 */
                position: relative;

                .timeline-current-indicator {
                    position: absolute;
                    top: 0;
                    bottom: 0;
                    width: 2px;
                    background-color: #ff9800;
                    /* 橙色 */
                    z-index: 100;
                    /* 较高的z-index确保显示在上层 */
                    left: 0;
                    pointer-events: none;
                    /* 使用transform代替left，获得更好的性能 */
                    transform: translateX(0);
                    will-change: transform;

                    &::before {
                        content: '';
                        position: absolute;
                        top: 0;
                        left: -5px;
                        width: 12px;
                        height: 12px;
                        background-color: #ff9800;
                        /* 橙色 */
                        border-radius: 50%;
                        cursor: ew-resize;
                        pointer-events: auto;
                    }
                }

                .timeline-ruler {
                    height: 24px;
                    background-color: var(--card-color);
                    border-bottom: 1px solid var(--border-color-base);
                    overflow: hidden;
                    position: relative;

                    .timeline-ruler-inner {
                        height: 100%;
                        position: relative;
                        margin-right: 50px;
                        /* 添加右侧边距，确保末尾可见 */

                        .timeline-tick {
                            position: absolute;
                            top: 0;
                            height: 100%;
                            width: 1px;
                            background-color: var(--border-color-base);

                            &:nth-child(10n) {
                                background-color: var(--text-color-secondary);
                            }

                            .tick-label {
                                position: absolute;
                                top: 4px;
                                left: 4px;
                                font-size: 10px;
                                color: var(--text-color-secondary);
                            }
                        }
                    }
                }

                .timeline-tracks-content {
                    flex: 1;
                    position: relative;
                    overflow: visible;
                    /* 允许内容溢出，使用父容器的滚动条 */

                    .timeline-track-content {
                        height: 30px;
                        border-bottom: 1px solid var(--border-color-base);
                        position: relative;
                        overflow: visible;
                        /* 允许内容溢出，使用父容器的滚动条 */
                        padding-right: 50px;
                        /* 添加右侧填充，确保内容完全显示 */
                        box-sizing: border-box;

                        &.selected {
                            background-color: var(--primary-color-pressed) !important;
                            border-top: 2px solid var(--primary-color);
                            border-bottom: 2px solid var(--primary-color);
                        }

                        &.locked {
                            background-color: rgba(0, 0, 0, 0.05);
                        }

                        &.hidden {
                            opacity: 0.5;
                        }

                        .timeline-track-drop-area {
                            position: absolute;
                            top: 0;
                            left: 0;
                            right: 0;
                            bottom: 0;
                            z-index: 1;
                        }

                        .keyframe {
                            position: absolute;
                            top: 10px;
                            width: 10px;
                            height: 10px;
                            background-color: var(--primary-color);
                            border-radius: 50%;
                            transform: translateX(-5px);
                            cursor: ew-resize;
                            z-index: 2;

                            &.selected {
                                box-shadow: 0 0 0 2px #fff, 0 0 0 4px var(--primary-color);
                            }
                        }

                        .clip {
                            position: absolute;
                            height: 20px;
                            top: 5px;
                            background-color: rgba(var(--primary-color-rgb), 0.3);
                            border: 1px solid var(--primary-color);
                            border-radius: 4px;
                            cursor: move;
                            z-index: 2;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            overflow: hidden;

                            /* 确保右侧不被截断 */
                            &:last-child {
                                margin-right: 0;
                            }

                            .clip-label {
                                font-size: 10px;
                                white-space: nowrap;
                                overflow: hidden;
                                text-overflow: ellipsis;
                                padding: 0 4px;
                            }

                            .clip-handle {
                                position: absolute;
                                top: 0;
                                bottom: 0;
                                width: 5px;
                                cursor: ew-resize;
                                z-index: 3;

                                &.left {
                                    left: 0;
                                }

                                &.right {
                                    right: 0;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</style>